<template>
  <div
    v-if="!initializing"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  >
    <el-image-viewer
      v-if="showViewer"
      :z-index="5000"
      :url-list="[imageUrl]"
      @close="() => showViewer = false"
      hide-on-click-modal
      teleported
    />

    <div
      v-if="!(showPdf && fileList.length <= 1) && title && fileList && fileList.length > 0"
      :style="visual.parseFontStyle(currNode.currCompStyle)"
    >{{title}}</div>
    <span
      v-if="!(showPdf && fileList.length <= 1)"
      v-for="(item, index) in fileList"
      :key="index"
      class="cc-file"
    >
      <span class="cc-file-item">
        <span class="cc-file-name" :title="item.name">
          <span style="cursor: pointer" v-if="isKnowFile(item)">
            <span @click="showFile(item)">{{item.name}}</span>
          </span>
          <span style="cursor: pointer" v-else-if="isImage(item)">
            <span @click="showImage(item)">{{item.name}}</span>
          </span>
          <span v-else><span>{{item.name}}</span></span>
        </span>
        <span class="cc-file-download">
          <cc-icon
            style="color: #409EFF;font-size: 16px;"
            iconId="018dc9c3efed1f464d38"
            title="下载"
            @click="downloadFile(item)"
          />
        </span>
      </span>
    </span>
    <div v-if="showPdf && pdfUrl">
      <iframe
        :style="`width:${width};height:${width};min-height:900px;border:none`"
        :src="pdfUrl"
      ></iframe>
    </div>
  </div>

  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    class="no-padding"
    append-to-body
    destroy-on-close
    draggable
    fullscreen
  >
    <vue-office-docx
      v-if="dialogFileType === 'word'"
      class="docx"
      :src="dialogUrl"
      :options="dialogOptions"
    />
    <vue-office-excel
      v-if="dialogFileType === 'excel'"
      :src="dialogUrl"
      :options="dialogOptions"
    />
  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, inject, nextTick, onMounted, ref } from 'vue';
import api from '@/http/api';
import loading from '@/utils/loading';
import { ElMessage } from 'element-plus';
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'

import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import EventHandler from "@/visual/js/event";
import visual from "@/visual/js/visual";

const props = defineProps({
  node: Object,
  inputParam: Object
});
const initializing = ref(true);
const currNode = ref(props.node);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);
const affixId = ref('');
const title = ref('');
const showPdf = ref(false);
const width = ref('');
const height = ref('');
const pdfUrl = ref('');
const fileList = ref([]);
const baseImageUrl = ref(import.meta.env.VITE_IMAGE_PATH);
const showViewer = ref(false);
const imageUrl = ref('');

const loadingPdf = ref(false);
const dialogTitle = ref('');
const dialogVisible = ref(false);
const dialogFileType = ref('');
const dialogUrl = ref('');
const dialogOptions = ref({});

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  title.value = currNode.value.currCompStyle['title'] || '';
  showPdf.value = currNode.value.currCompStyle['showPdf'] || false;
  width.value = currNode.value.currCompStyle['width'] || '';
  height.value = currNode.value.currCompStyle['height'] || '';
  await nextTick(() => initializing.value = false);
};

const isImage = (file) => {
  return file.name.toLowerCase().endsWith('.png')
    || file.name.toLowerCase().endsWith('.jpeg')
    || file.name.toLowerCase().endsWith('.jpg')
    || file.name.toLowerCase().endsWith('.bmp')
    || file.name.toLowerCase().endsWith('.gif')
};

const showImage = (file) => {
  imageUrl.value = '';
  if (file && file.id) {
    imageUrl.value = baseImageUrl.value + file.id;
    showViewer.value = true;
  }
};

const downloadFile = (file) => {
  api.downloadFileLocal(file.id);
};

const loadData = () => {
  pdfUrl.value = '';
  fileList.value = [];
  if (affixId.value) {
    api.queryAffix(affixId.value).then((res) => {
      if(res.data.length > 0){
        for (let i=0;i<res.data.length;i++) {
          const file = {name: res.data[i].trueName || '', id: res.data[i].id, status: 2};
          fileList.value.push(file);
          if (showPdf.value
              && !pdfUrl.value
              && file.name.toLowerCase().endsWith('.pdf')) {
            showFile(file);
          }
        }
      }
    }).catch((res) => {
      ElMessage.error(res.message);
    });
  }
};

const isKnowFile = (file) => {
  return file.name.toLowerCase().endsWith('.pdf')
    || file.name.toLowerCase().endsWith('.ofd')

    || file.name.toLowerCase().endsWith('.doc')
    || file.name.toLowerCase().endsWith('.docx')
    || file.name.toLowerCase().endsWith('.wps')

    || file.name.toLowerCase().endsWith('.ppt')
    || file.name.toLowerCase().endsWith('.pptx')

    || file.name.toLowerCase().endsWith('.xls')
    || file.name.toLowerCase().endsWith('.xlsx')
    || file.name.toLowerCase().endsWith('.et')
};

const showFile = (file) => {
  dialogUrl.value = '';
  dialogOptions.value = {};
  if (file.name.toLowerCase().endsWith('.pdf')) {
    if (loadingPdf.value) return;
    loadingPdf.value = true;
    loading.showLoading("文件加载中，请稍候...");
    api.download(file.id).then((res) => {
      let blob = new Blob([res.data], {type: 'application/pdf'})
      let href = window.URL.createObjectURL(blob);
      if (showPdf.value) {
        pdfUrl.value = href;
      } else {
        window.open(href, '_blank');
      }
      loadingPdf.value = false;
      loading.hideLoading();
    }).catch((res) => {
      loadingPdf.value = false;
      ElMessage.error(res.message);
      loading.hideLoading();
    });
  } else if (file.name.toLowerCase().endsWith('.docx')) {
    dialogTitle.value = "文件查看【" + file.name + "】"
    dialogUrl.value = baseImageUrl.value + file.id;
    dialogFileType.value = "word";
    dialogVisible.value = true;
  } else if (file.name.toLowerCase().endsWith('.xlsx') || file.name.toLowerCase().endsWith('.xls')) {
    dialogTitle.value = "文件查看【" + file.name + "】"
    dialogUrl.value = baseImageUrl.value + file.id;
    dialogFileType.value = "excel";
    dialogVisible.value = true;
    dialogOptions.value = {
      xls: file.name.toLowerCase().endsWith('.xls')
    }
  }
};

const loadValue = async() => {
  const dataList = (await visual.loadData(
    currNode.value.compData,
    eventHandler,
    getData(),
    currNode.value)).data || [];
  affixId.value = dataList.length > 0 && dataList[0]['内容'] || '';
  loadData();
};

const getData = () => {
  return {
    inputParam: Object.assign({}, currNode.value.inputParam, props.inputParam),
    value: affixId.value
  };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = async() => {
  initializing.value = true;
  await loadValue();
  await nextTick(() => initializing.value = false);
};

onMounted(async() => {
  await init();
  await loadValue();
  await eventHandler.trigger('初始化事件');
});

defineExpose({ getData, changeStyle, refresh });
</script>

<style scoped>
.cc-affix {
  width: 100%;
  text-align: left;
  margin-bottom: 5px;
}
.cc-file {
  width: 100%;
  line-height: 25px;
}
.cc-file-item {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
}
.cc-file-name {
  overflow: hidden;
  min-width: 0;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.cc-file-name > div {
  margin-right: 8px;
}

.cc-file-name > div > div {
  display: flex;
  height: 18px;
  align-items: center;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.cc-file-download {
  font-size: 18px;
  cursor: pointer;
  margin-left: 5px;
  width: 25px;
}
.cc-file-download:hover {
  color: #409EFF;
}
.docx :deep(.docx) {
  padding: 72pt 89.76pt;
  width: 595.28pt;
}
</style>
